import router from "./router";
import store from "./store";
import {
  Message
} from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import {
  get_localUserInfo,
  set_localToken,
  set_localUserInfo,
  delect_localUserInfo
} from "./common/localStorageAPI";
import {
  get_user_login
} from "./api/user_login";

NProgress.configure({
  showSpinner: false
}); // NProgress Configuration

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start();
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title;
  }
  let userNumber = get_localUserInfo();
  // console.log("路由拦截", userNumber);

  if (userNumber) {
    if (store.getters.userInfo) {
      // console.log("已登录路", store.getters.userInfo);
      if (to.path == "/" || to.path == "/register" || to.path == "/forget") {
        next("/home");
        NProgress.done();
      } else {
        next();
        NProgress.done();
      }

    } else {
      let oldTime = Date.parse(userNumber.date);
      let nowTime = Date.parse(new Date());
      let day = (nowTime - oldTime) / (1000 * 60 * 60);
      // console.log("时间差", day);
      if (day < 24) {
        let resData = await get_user_login({
          phone: userNumber.phone,
          password: userNumber.password
        });
        // console.log("自动登录", resData);
        store.commit("SET_USERINFO", resData.data[0]);
        store.commit("SET_TOKEN", resData.token);
        set_localToken(resData.token);
        set_localUserInfo({
          phone: resData.data[0].phone,
          password: resData.data[0].password,
          date: userNumber.date
        });
        if (to.path == "/" || to.path == "/register" || to.path == "/forget") {
          next("/home");
          NProgress.done();
        } else {
          next();
          NProgress.done();
        }
      } else {
        console.log("超时登录");
        delect_localUserInfo();
        Message.error("登录过期，请重新登录");
        next(`/?redirect=${to.fullPath}`)
        NProgress.done();

      }
    }
  } else {
    console.log("没登录保存状态");
    // console.log("没登录保存状态", to.fullPath);

    if (to.path == "/" || to.path == "/register" || to.path == "/forget") {
      //如果是登录页面路径，就直接next()
      next();
      NProgress.done();
    } else {
      //不然就跳转到登录；
      // next("/");
      next(`/?redirect=${to.fullPath}`)
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  window.scrollTo(0, 0);
  NProgress.done();

  // setTimeout(() => {
  //   NProgress.done();
  // }, 2000);
});